<template>
	<div class="chat-msg-item">
		<div class="chat-msg-tip"
			v-if="msgInfo.type == $enums.MESSAGE_TYPE.RECALL || msgInfo.type == $enums.MESSAGE_TYPE.TIP_TEXT">
			{{ msgInfo.content }}
		</div>
		<div class="chat-msg-tip" v-if="msgInfo.type == $enums.MESSAGE_TYPE.TIP_TIME">
			{{ $date.toTimeText(msgInfo.sendTime) }}
		</div>
		<div class="chat-msg-normal" v-if="isNormal" :class="{ 'chat-msg-mine': mine }">
			<div class="head-image">
				<head-image :name="showName" :size="40" :url="headImage" :id="msgInfo.sendId"></head-image>
			</div>
			<div class="chat-msg-content">
				<div v-show="mode == 1 && msgInfo.groupId && !msgInfo.selfSend" class="chat-msg-top">
					<span>{{ showName }}</span>
				</div>
				<div v-show="mode == 2" class="chat-msg-top">
					<span>{{ showName }}</span>
					<span>{{ $date.toTimeText(msgInfo.sendTime) }}</span>
				</div>
				<div class="chat-msg-bottom" @contextmenu.prevent="showRightMenu($event)">
					<div ref="chatMsgBox">
						<span class="chat-msg-text" v-if="msgInfo.type == $enums.MESSAGE_TYPE.TEXT" v-highlight="handleHighlight"
							v-html="$emo.transform(msgInfo.content)"></span>
						<div class="chat-msg-image" v-if="msgInfo.type == $enums.MESSAGE_TYPE.IMAGE">
							<div class="img-load-box" v-loading="loading" element-loading-text="上传中.."
								element-loading-background="rgba(0, 0, 0, 0.4)">
								<img class="send-image" :src="JSON.parse(msgInfo.content).thumbUrl"
									@click="showFullImageBox()" loading="lazy" />
							</div>
							<span title="发送失败" v-show="loadFail" @click="onSendFail"
								class="send-fail el-icon-warning"></span>
						</div>
						<div class="chat-msg-file" v-if="msgInfo.type == $enums.MESSAGE_TYPE.FILE">
							<div class="chat-file-box" v-loading="loading">
								<div class="chat-file-info">
									<el-link class="chat-file-name" :underline="false" target="_blank" type="primary" @click="showFullFile(data.url)"
										>{{ data.name }}</el-link>
									<div class="chat-file-size">{{ fileSize }}</div>
								</div>
								<div class="chat-file-icon">
									<span type="primary" class="el-icon-document"></span>
								</div>
								<el-progress 
									v-if="!loadFail && progressInfo.progressShow && progressInfo.progressIndex === msgInfo.id" 
									style="margin-left: -35px"
									type="circle" 
									:width="20" 
									:stroke-width="2" 
									:percentage="progressInfo.progress" 
									:status="progressInfo.progressStatus"></el-progress>
							</div>
							<span title="发送失败" v-show="loadFail" @click="onSendFail"
								class="send-fail el-icon-warning"></span>
						</div>
					</div>
					<div class="chat-msg-voice" v-if="msgInfo.type == $enums.MESSAGE_TYPE.AUDIO" @click="onPlayVoice()">
						<audio controls :src="JSON.parse(msgInfo.content).url"></audio>
					</div>
					<div class="chat-action chat-msg-text" v-if="isAction">
						<span v-if="msgInfo.type==$enums.MESSAGE_TYPE.ACT_RT_VOICE" title="重新呼叫" @click="$emit('call')"
							class="iconfont icon-chat-voice"></span>
						<span v-if="msgInfo.type==$enums.MESSAGE_TYPE.ACT_RT_VIDEO" title="重新呼叫" @click="$emit('call')"
							class="iconfont icon-chat-video"></span>
						<span>{{msgInfo.content}}</span>
					</div>
					<div class="chat-msg-status" v-if="!isAction">
						<span class="chat-readed" v-show="msgInfo.selfSend && !msgInfo.groupId
						&& msgInfo.status == $enums.MESSAGE_STATUS.READED">已读</span>
						<span class="chat-unread" v-show="msgInfo.selfSend && !msgInfo.groupId
						&& msgInfo.status != $enums.MESSAGE_STATUS.READED">未读</span>
					</div>
					<div class="chat-receipt" v-show="msgInfo.receipt" @click="onShowReadedBox">
						<span v-if="msgInfo.receiptOk" class="icon iconfont icon-ok" title="全体已读"></span>
						<span v-else>{{msgInfo.readedCount}}人已读</span>
					</div>

				</div>
			</div>

		</div>
		<right-menu v-show="menu && rightMenu.show" :pos="rightMenu.pos" :items="menuItems"
			@close="rightMenu.show = false" @select="onSelectMenu"></right-menu>
		<chat-group-readed ref="chatGroupReadedBox" :msgInfo="msgInfo" :groupMembers="groupMembers"></chat-group-readed>
	</div>
</template>
<script>
	import HeadImage from "../common/HeadImage.vue";
	import RightMenu from '../common/RightMenu.vue';
	import ChatGroupReaded from './ChatGroupReaded.vue';
	export default {
        // 在Vue组件中定义自定义指令
        directives: {
            highlight: {
                bind(el, binding) {
                    el.addEventListener('mouseup', () => {
                        const selection = window.getSelection().toString();
                        if (selection.length > 0) {
                            binding.value(selection);
                        }
                    });
                }
            }
        },
		name: "messageItem",
		components: {
			HeadImage,
			RightMenu,
			ChatGroupReaded
		},
		props: {
			mode: {
				type: Number,
				default: 1
			},
			mine: {
				type: Boolean,
				required: true
			},
			headImage: {
				type: String,
				required: true
			},
			showName: {
				type: String,
				required: true
			},
			msgInfo: {
				type: Object,
				required: true
			},
			groupMembers: {
				type: Array
			},
			menu: {
				type: Boolean,
				default: true
			},
			progressInfo: {
				type: Object
			}
		},
		data() {
			return {
				audioPlayState: 'STOP',
				rightMenu: {
					show: false,
					pos: {
						x: 0,
						y: 0
					}
				}
			}

		},
		methods: {
            //复制文字文本
            handleHighlight(text) {
                console.log('用户选择的文本:', text);
                this.msgInfo.selectText = text;
            },
			onSendFail() {
				this.$message.error("该文件已发送失败，目前不支持自动重新发送，建议手动重新发送")
			},
            showFullFile(url) {
                console.log("file:" + url);//http://192.168.10.16:9000/box-im/file/20240831/1725080577460.pdf

                // 创建一个新的 URL 对象来解析传入的文件 URL
                const fileUrlObj = new URL(url);

                // 获取协议、主机名和端口号（即基础 URL）
                const minioUrlPathName = fileUrlObj.pathname;
                console.log(minioUrlPathName);


                const isDevelopment = process.env.NODE_ENV !== 'production';
                const urlopen = new URL(window.location.href);
                console.log("urlopen:" + urlopen);// urlopen https://192.168.10.75:7543/exe/outside

                const baseUrl = urlopen.origin;//拿到请求的url
                console.log("baseUrl:" + baseUrl);
                console.log("isDevelopment:" + isDevelopment);
                let requestUrl=baseUrl;
                if(isDevelopment){
                    requestUrl="https://110.249.128.122:7543";
                }else {
                    url=requestUrl+minioUrlPathName
                    // 这里主要处理内网打不开
                    console.log("url:" + url);
                    if(requestUrl.includes("192.168.10.75")||requestUrl.includes("10.0.9.202")){
                        window.open(requestUrl+'/preview1/onlinePreview?url=' + encodeURIComponent(window.Base64.encode(url)));
                        return;
                    }


                }
                // window.open('http://192.168.10.75:8012/onlinePreview?url=' + encodeURIComponent(window.Base64.encode(url)));
                window.open(requestUrl+'/preview/onlinePreview?url=' + encodeURIComponent(window.Base64.encode(url)));

            },
			showFullImageBox() {
				let imageUrl = JSON.parse(this.msgInfo.content).originUrl;
				if (imageUrl) {
					this.$store.commit('showFullImageBox', imageUrl);
				}
			},
			onPlayVoice() {
				if (!this.audio) {
					this.audio = new Audio();
				}
				this.audio.src = JSON.parse(this.msgInfo.content).url;
				this.audio.play();
				this.onPlayVoice = 'RUNNING';
			},
			showRightMenu(e) {
                // 右键时，通过Selection API来选中文本
                const selection = window.getSelection();
                const range = document.createRange();
                range.selectNodeContents(e.target);
                selection.removeAllRanges();
                selection.addRange(range);

				this.rightMenu.pos = {
					x: e.x,
					y: e.y
				};
				this.rightMenu.show = "true";
			},
			onSelectMenu(item) {
				this.$emit(item.key.toLowerCase(), this.msgInfo);
			},
			onShowReadedBox() {
				let rect = this.$refs.chatMsgBox.getBoundingClientRect();
				this.$refs.chatGroupReadedBox.open(rect);
			}
		},
		computed: {
			loading() {
				return this.msgInfo.loadStatus && this.msgInfo.loadStatus === "loading";
			},
			loadFail() {
				return this.msgInfo.loadStatus && this.msgInfo.loadStatus === "fail";
			},
			data() {
				return JSON.parse(this.msgInfo.content)
			},
			fileSize() {
				let size = this.data.size;
				if (size > 1024 * 1024) {
					return Math.round(size / 1024 / 1024) + "M";
				}
				if (size > 1024) {
					return Math.round(size / 1024) + "KB";
				}
				return size + "B";
			},
			menuItems() {
				let items = [];
				/*items.push({
					key: 'DELETE',
					name: '删除',
					icon: 'el-icon-delete'
				});
				if (this.msgInfo.selfSend && this.msgInfo.id > 0) {
					items.push({
						key: 'RECALL',
						name: '撤回',
						icon: 'el-icon-refresh-left'
					});
				}*/
                if ((this.msgInfo.type == this.$enums.MESSAGE_TYPE.FILE || this.msgInfo.type == this.$enums.MESSAGE_TYPE.IMAGE) && this.msgInfo.id > 0) {
                    items.push({
                        key: 'SAVE',
                        name: '保存',
                        icon: 'el-icon-download'
                    });
                }
                if ((this.msgInfo.type == this.$enums.MESSAGE_TYPE.TEXT && this.msgInfo.id > 0 ) || this.msgInfo.type == this.$enums.MESSAGE_TYPE.IMAGE) {
                        items.push({
                        key: 'COPY',
                        name: '复制',
                        icon: 'el-icon-document-copy'
                    });
                }
                if ((this.msgInfo.type == this.$enums.MESSAGE_TYPE.TEXT && this.msgInfo.id > 0)|| this.msgInfo.type == this.$enums.MESSAGE_TYPE.IMAGE  ) {
                    items.push({
                        key: 'APPOINT',
                        name: '引用',
                        icon: 'el-icon-chat-line-square'
                    });
                }
				return items;
			},
			isAction(){
				return this.$msgType.isAction(this.msgInfo.type);
			},
			isNormal() {
				const type = this.msgInfo.type;
				return this.$msgType.isNormal(type) || this.$msgType.isAction(type)
			}
		},mounted() {
            // 确保在组件挂载后加载第三方JS
            const script = document.createElement('script');
            script.src = process.env.BASE_URL +'base64.js';
            script.onload = () => {
                // 第三方脚本加载完成后的回调
                console.log('第三方脚本加载完成');
            };
            document.head.appendChild(script);
        },
	}
</script>

<style lang="scss">
	.chat-msg-item {

		.chat-msg-tip {
			line-height: 36px;
			font-size: 12px;
			 color: #8e9ab0;
		}

		.chat-msg-normal {
			position: relative;
			font-size: 0;
			padding-left: 60px;
			min-height: 50px;
			margin-top: 10px;

			.head-image {
				position: absolute;
				width: 30px;
				height: 30px;
				top: 0;
				left: 0;
			}

			.chat-msg-content {
				text-align: left;

				.send-fail {
					color: #e60c0c;
					font-size: 30px;
					cursor: pointer;
					margin: 0 20px;
				}

				.chat-msg-top {
					display: flex;
					flex-wrap: nowrap;
					color: #8e9ab0;
                    font-size: 12px;
					line-height: 20px;

					span {
						margin-right: 12px;
					}
				}

				.chat-msg-bottom {
					display: inline-block;
					padding-right: 300px;

					.chat-msg-text {
						display: block;
						position: relative;
						line-height: 26px;
						margin-top: 3px;
						padding: 7px;
						background-color:#f4f5f7;
						border-radius: 4px;
						color: #344450;
						display: block;
						font-size: 14px;
						text-align: left;
						white-space: pre-wrap;
						word-break: break-all;
						box-shadow: 1px 1px 1px #eeeeee;

						&:after {
							content: "";
							position: absolute;
							left: -10px;
							top: 13px;
							width: 0;
							height: 0;
							border-style: solid dashed dashed;
							border-color:#f4f5f7 transparent transparent;
							overflow: hidden;
							border-width: 10px;
						}
					}

					.chat-msg-image {
						display: flex;
						flex-wrap: nowrap;
						flex-direction: row;
						align-items: center;

						.send-image {
							/*min-width: 200px;*/
							/*min-height: 150px;*/
							max-width: 400px;
							max-height: 200px;
							border-radius: 4px;
							cursor: pointer;
                          object-fit:cover;
						}

					}

					.chat-msg-file {
						display: flex;
						flex-wrap: nowrap;
						flex-direction: row;
						align-items: center;
						cursor: pointer;
						padding-bottom: 5px;

						.chat-file-box {
							display: flex;
							flex-wrap: nowrap;
							align-items: center;
							min-height: 60px;
							border: #dddddd solid 1px;
							border-radius: 4px;
							padding: 10px 10px;

							.chat-file-info {
								flex: 1;
								height: 100%;
								text-align: left;
								font-size: 14px;

								.chat-file-name {
									display: inline-block;
									min-width: 150px;
									max-width: 300px;
									font-size: 14px;
									font-weight: 600;
									margin-bottom: 10px;
									white-space: pre-wrap;
									word-break: break-all;
								}
							}

							.chat-file-icon {
								font-size: 50px;
								color: #d42e07;
							}

							.el-progress {
								margin-left: -35px;
								margin-right: 15px;
							}
						}

						.send-fail {
							color: #e60c0c;
							font-size: 30px;
							cursor: pointer;
							margin: 0 20px;
						}

					}

					.chat-msg-voice {
						font-size: 14px;
						cursor: pointer;

						audio {
							height: 45px;
							padding: 5px 0;
						}
					}

					.chat-action {
						display: flex;
						align-items: center;

						.iconfont {
							cursor: pointer;
							font-size: 22px;
							padding-right: 8px;
						}
					}

					.chat-msg-status {
						display: block;

						.chat-readed {
							font-size: 12px;
							color:  rgb(2 137 250 );
							font-weight: 400;
						}

						.chat-unread {
							font-size: 12px;
							color: #f23c0f;
							font-weight: 400;
						}
					}

					.chat-receipt {
						font-size: 13px;
						color: rgb(2 137 250 );
						cursor: pointer;

						.icon-ok {
							font-size: 20px;
							color: #329432;
						}
					}
				}
			}


			&.chat-msg-mine {
				text-align: right;
				padding-left: 0;
				padding-right: 60px;

				.head-image {
					left: auto;
					right: 0;
				}

				.chat-msg-content {
					text-align: right;

					.chat-msg-top {
						flex-direction: row-reverse;


						span {
							margin-left: 12px;
							margin-right: 0;
						}
					}

					.chat-msg-bottom {
						padding-left: 180px;
						padding-right: 0;

						.chat-msg-text {
							margin-left: 10px;
							background-color:#cce7fe;
							color: #344450;
							vertical-align: top;
							box-shadow: 1px 1px 1px #e7e7e7;

							&:after {
								left: auto;
								right: -10px;
								border-top-color: #cce7fe;
							}
						}

						.chat-msg-image {
							flex-direction: row-reverse;
						}

						.chat-msg-file {
							flex-direction: row-reverse;
						}

						.chat-action {
							flex-direction: row-reverse;

							.iconfont {
								transform: rotateY(180deg);
							}
						}
					}
				}
			}

		}
	}
</style>
